﻿#pragma once
#include "_utilsinc.h"

class NodeSnatch
{
public:
	virtual ~NodeSnatch();
	enum class eState{ Normal, Cross, Down, None };
	enum class eDrag { None, H, V, Both };
	virtual void setEnabled(bool isEnabled);
	virtual bool isEnabled()const{ return _isEnabled; }
	virtual void setSortable(bool isSortable){ _isSortable = isSortable; }
	
	virtual void setDragType(const eDrag& e){ _dragType = e; }
	virtual void setScrollSpeed(int speed){ _scrollSpeed = speed; }

	virtual void addChildSnatch(NodeSnatch *nodeSnatch, bool isAddchildForNodeTarget = true);
protected:
	virtual void removeChildSnatch(NodeSnatch *nodeSnatch);

	virtual bool init(Node* node);
	virtual bool isBox(const Vec2& worldSpace);
	virtual void setState(const eState& state){}
	virtual void doClick(const Vec2& location, bool isActiveForListener){}
	virtual void doRup(const Vec2& location){}
	virtual void doKeep(float delta){}
	
	virtual Node* getDragableNode(){ return _nodeTarget; }
	virtual void doDraging(const Vec2& worldSpace){}

	bool _isEnabled = true;
	bool _isSortable = false;
	Node* _nodeTarget = nullptr;
	eDrag _dragType = eDrag::None;
	int _scrollSpeed = 0;

	vector<NodeSnatch*> _children;
	NodeSnatch* _parent = nullptr;
	friend class ListenerSnatch;
};


class ListenerSnatch : public EventListenerTouchOneByOne
{
public:
	virtual ~ListenerSnatch();
	static ListenerSnatch* create(Node* node){ CREATE(ListenerSnatch, node); }
	virtual void addChildSnatch(NodeSnatch *nodeSnatch, bool isAddchildForNodeTarget = true);
protected:
//	virtual void removeChildSnatch(NodeSnatch *nodeSnatch);
	virtual bool init(Node* node);
private:
	void sortChildren();
	static NodeSnatch* getChildSnatch(const vector<NodeSnatch*>& children, const Vec2& worldSpace);
	static void recurClick(vector<NodeSnatch*>& children, const Vec2& worldSpace, const NodeSnatch* curr);
	virtual NodeSnatch* getChildSnatch(const Vec2& worldSpace);
	bool compareTops(NodeSnatch* top, NodeSnatch* old, bool isTouching);
	virtual void update(float delta);

	Node* _nodeTarget = nullptr;
	vector<NodeSnatch*> _children;

	NodeSnatch* _curr = nullptr;
	Vec2 _vecDrag, _vecStartLocation;
	bool _isDragThreshold = false;
	
	int _z = 0;
	float _delta;
	string _shedulerKey;
	bool _isSheduling = false;
};